const express = require('express');
const router = express.Router();
const db = require('../db/index.js');
const md5 = require('md5');

/* GET users listing. */
router.get('/', async (req, res, next) => {
  try {
    // 获取所有用户
    const [users] = await db.execute('SELECT * FROM users');
    res.status(200).json({ code: 0, data: users });
  } catch (error) {
    console.log(error);
    res.status(500).send('服务器错误');
  }
});

// 用户注册接口
router.post('/register', async (req, res) => {
  const { username, password } = req.body;

  // 验证前端传入的用户名和密码是否为空
  if (!username || !password) {
    return res.status(400).json({ error: '用户名和密码是必填项!' });
  }

  try {
    // 检查用户名是否已存在
    const checkSql = 'SELECT * FROM users WHERE username =?';
    console.log('username', username);

    const [existingUsers] = await db.query(checkSql, [username]);
    console.log('existingUsers', existingUsers);

    if (existingUsers.length > 0) {
      return res.status(409).json({ error: '用户已经存在!' });
    }

    // 插入新用户数据的SQL语句
    const insertSql = 'INSERT INTO users (username, password) VALUES (?,?)';
    const [result] = await db.execute(insertSql, [username, md5(password)]);
    // 插入用户基础信息
    const insertBaseInfoSql =
      'INSERT INTO user_info (user_id, address, phone) VALUES (?,?,?)';
    await db.execute(insertBaseInfoSql, [result.insertId, '', '']);

    res
      .status(201)
      .json({ message: '用户注册成功', insertedId: result.insertId });
  } catch (error) {
    res.status(500).json({ error: '服务出现错误❎' });
  }
});

// 删除用户
router.delete('/delete', async (req, res) => {
  const { id } = req.query;

  // 验证前端传入的用户名和密码是否为空
  if (!id) {
    return res.status(400).json({ error: 'id is required' });
  }

  try {
    // 检查用户名是否已存在
    const checkSql = 'SELECT * FROM users WHERE id =?';
    const [existingUsers] = await db.query(checkSql, [id]);

    if (!existingUsers.length) {
      return res.status(409).json({ error: '该用户不存在~' });
    }
    const deleteSql = 'DELETE FROM users WHERE id = ?';
    await db.execute(deleteSql, [id]);

    res.status(201).json({ message: '用户注销成功' });
  } catch (error) {
    res.status(500).json({ error: '服务出现错误❎' });
  }
});

// 更新用户基础信息
router.post('/update', async (req, res) => {
  const { id, address, phone, name } = req.body;

  // 验证前端传入的用户名和密码是否为空
  if (!id) {
    return res.status(400).json({ error: 'id is required' });
  }

  try {
    // 检查用户名是否已存在
    const checkSql = 'SELECT * FROM users WHERE id =?';
    const [existingUsers] = await db.query(checkSql, [id]);

    if (!existingUsers.length) {
      res.status(201).json({ message: '该用户不存在~' });
      return;
    }

    const updateSql =
      'UPDATE user_info SET address =?, phone =?, name =? WHERE user_id = ?';
    await db.execute(updateSql, [address, phone, name, id]);
    res.status(200).json({ message: '用户信息修改成功' });
  } catch (error) {
    res.status(500).json({ error: error });
  }
});

module.exports = router;
